package cn.kgc.tangcco.handler;

import cn.kgc.tangcco.dao.ClazzDao;
import cn.kgc.tangcco.pojo.Clazz;
import cn.kgc.tangcco.service.ClazzService;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @author 李昊哲
 * @Description
 * @create 2021/1/22 13:26
 */
@Component
public class ClazzHandler {
    private final ClazzService clazzService;
    private final ClazzDao clazzDao;

    public ClazzHandler(ClazzService clazzService, ClazzDao clazzDao) {
        this.clazzService = clazzService;
        this.clazzDao = clazzDao;
    }

    public Mono<ServerResponse> save(ServerRequest request) {
        Mono<Clazz> mono = request.bodyToMono(Clazz.class);
        Clazz clazz = mono.block();
        return ServerResponse
                .ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(clazzDao.save(clazz), Clazz.class);
    }

    public Mono<ServerResponse> findById(ServerRequest request) {
        String id = request.pathVariable("id");
        return ServerResponse
                .ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(clazzService.findById(Integer.parseInt(id)), Clazz.class);
    }

    public Mono<ServerResponse> findAll(ServerRequest request) {
        return ServerResponse
                .ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(clazzService.findAll(), Clazz.class);
    }
}
